package cn.echase.ecare.yinfayun.service.impl;

import cn.echase.common.core.exception.EchaseException;
import cn.echase.ecare.operate.manager.api.domain.vo.RemoteFormInfoVo;
import cn.echase.ecare.operate.manager.api.service.IRemoteFormInfoService;
import cn.echase.ecare.yinfayun.constants.AssessConstant;
import cn.echase.ecare.yinfayun.domain.dto.AssessBaseResDto;
import cn.echase.ecare.yinfayun.domain.dto.AssessInfoDto;
import cn.echase.ecare.yinfayun.domain.dto.AssessTemplateDto;
import cn.echase.ecare.yinfayun.domain.dto.GetAssessInfoReqDto;
import cn.echase.ecare.yinfayun.domain.entity.AssessInfo;
import cn.echase.ecare.yinfayun.domain.entity.AssessInfoResult;
import cn.echase.ecare.yinfayun.domain.mapper.AssessInfoMapper;
import cn.echase.ecare.yinfayun.domain.vo.AssesElderMedicineVo;
import cn.echase.ecare.yinfayun.domain.vo.AssessInfoExportVo;
import cn.echase.ecare.yinfayun.domain.vo.AssessInfoVo;
import cn.echase.ecare.yinfayun.service.IAssessInfoResultService;
import cn.echase.ecare.yinfayun.service.IAssessInfoService;
import cn.echase.ecare.yinfayun.service.IAssessTemplateService;
import cn.echase.ecare.yinfayun.utils.IntegerUtil;
import cn.echase.ecare.yinfayun.utils.JSONNodeUtil;
import cn.echase.ecare.yinfayun.utils.UcCommonUtils;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.validation.constraints.NotNull;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;

import static cn.echase.ecare.yinfayun.constants.AssessConstant.AssessCategoryCode.ASSES_TYPE;
import static cn.echase.ecare.yinfayun.constants.AssessConstant.AssessStatus.COMPLETE;
import static cn.echase.ecare.yinfayun.constants.AssessConstant.AssessStatus.UN_COMPLETE;
import static cn.echase.ecare.yinfayun.constants.AssessConstant.AssessStatusStr.COMPLETE_STR;
import static cn.echase.ecare.yinfayun.constants.AssessConstant.AssessStatusStr.UN_COMPLETE_STR;
import static cn.echase.ecare.yinfayun.constants.AssessConstant.IS_DELETED.DELETED;
import static cn.echase.ecare.yinfayun.constants.AssessConstant.IS_DELETED.UN_DELETED;
import static cn.echase.ecare.yinfayun.constants.AssessConstant.SUCCESS;
import static cn.echase.ecare.yinfayun.constants.AssessConstant.TemplateContentKey.*;

/**
 * @Title: AssessInfoServiceImpl
 * @Author  lidisong
 * @Package cn.echase.ecare.template.assess.service.impl
 * @Date  06/05/2025 星期二 11:30 上午
 * @description:
*/
@Slf4j
@RequiredArgsConstructor
@Service("assessInfoService")
public class AssessInfoServiceImpl extends ServiceImpl<AssessInfoMapper, AssessInfo> implements IAssessInfoService {

    @DubboReference
    private IRemoteFormInfoService remoteFormInfoService;

    @Autowired
    private IAssessTemplateService assessTemplateService;
    @Autowired
    private IAssessInfoResultService assessInfoResultService;

    @Override
    public JSONObject infoListExport(AssessInfoDto assessInfoDto) {
        assessInfoDto.setTenantId(assessInfoDto.getOrgId());
        //0 校验入参
        Assert.notBlank(assessInfoDto.getOrgId(), "机构ID不能为空！");

        List<AssessInfoExportVo> assessInfoExportVos = new ArrayList<>();
        // 评估信息列表（新）
        TableDataInfo<AssessInfoVo> assessInfoVoTableDataInfo = this.infoListRefactor(assessInfoDto);
        if (ObjUtil.isNotNull(assessInfoVoTableDataInfo)) {
            List<AssessInfoVo> assessInfoVoList = assessInfoVoTableDataInfo.getRows();
            if (CollUtil.isNotEmpty(assessInfoVoList)) {
                for (AssessInfoVo assessInfoVo : assessInfoVoList) {
                    AssessInfoExportVo assessInfoExportVo = new AssessInfoExportVo();
                    BeanUtils.copyProperties(assessInfoVo, assessInfoExportVo);
                    assessInfoExportVo.setAssessStatusName(assessInfoVo.getAssessStatus() == 1 ? UN_COMPLETE_STR : COMPLETE_STR);
                    assessInfoExportVo.setAssessorName(assessInfoVo.getAssessorOneName() + "，" + assessInfoVo.getAssessorTwoName());
                    assessInfoExportVos.add(assessInfoExportVo);
                }
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", assessInfoExportVos);
        jsonObject.put("count", assessInfoVoTableDataInfo == null ? assessInfoExportVos.size() : assessInfoVoTableDataInfo.getTotal());
        jsonObject.put("total", assessInfoVoTableDataInfo == null ? 1 : assessInfoVoTableDataInfo.getTotal());
        return jsonObject;
    }

    @Override
    public TableDataInfo<AssessInfoVo> infoListRefactor(AssessInfoDto assessInfoDto) {
        String deptId = String.valueOf(LoginHelper.getDeptId());
        log.info("[infoListRefactor]-infoListRefactor={}", JSONUtil.toJsonStr(assessInfoDto));

        // 查询评估信息
        int pageNum = assessInfoDto.getPageNum() == null ? 1 : assessInfoDto.getPageNum();
        Page<AssessInfo> iPage = new Page<>(pageNum, assessInfoDto.getPageSize());
        IPage<AssessInfoVo> assessInfoVoExist = this.selectListWithParams(iPage, assessInfoDto);

        // 评估模板ID,报告ID
        Map<String, String> reportIdMap = new HashMap<>();
        if (CollUtil.isNotEmpty(assessInfoVoExist.getRecords())){
            reportIdMap = this.fillReportId(deptId);
        }

        for (AssessInfoVo item : assessInfoVoExist.getRecords()) {
            if(StringUtil.isEmpty(item.getReportId())){
                String reportId = reportIdMap.get(item.getTemplateId());
                item.setReportId(reportId);
            }
        }

        log.info("[infoListRefactor]-pageInfo={}", JSONUtil.toJsonStr(assessInfoVoExist));
//        return TableDataInfo.build(SUCCESS, assessInfoVoExist);

        return null; // TODO 需做兼容
    }

    /**
     * 获取评估模板ID,报告ID
     */
    public Map<String, String> fillReportId(String deptId) {
        log.info("[fillReportId]-deptId={}", deptId);
        List<RemoteFormInfoVo> formInfoList = remoteFormInfoService.getFormInfoList(ASSES_TYPE, deptId);
        log.info("[fillReportId]-formInfoList={}", JSONUtil.toJsonStr(formInfoList));
        HashMap<String, String> reportIdMap = new HashMap<>();
        for (RemoteFormInfoVo remoteFormInfoVo : formInfoList) {
            String id = String.valueOf(remoteFormInfoVo.getId());
            String reportId = remoteFormInfoVo.getReportId();
            if (!reportIdMap.containsKey(id)) {
                reportIdMap.put(id, reportId);
            }
        }

        log.info("[fillReportId]-reportIdMap={}", JSONUtil.toJsonStr(reportIdMap));
        return reportIdMap;
    }

    /**
     * 根据条件查询评估列表
     */
    public List<AssessInfoVo> selectListWithParams(AssessInfoDto assessInfoDto) {
        LambdaQueryWrapper<AssessInfo> queryWrapper = this.getAssessInfoLambdaQueryWrapper(assessInfoDto);
        List<AssessInfoVo> assessInfoVoList = baseMapper.selectVoList(queryWrapper);
        log.info("[selectListWithParams]-assessInfoVoList={}", JSONUtil.toJsonStr(assessInfoVoList));
        return assessInfoVoList;
    }

    /**
     * 根据条件查询评估列表
     */
    public IPage<AssessInfoVo> selectListWithParams(Page<AssessInfo> iPage, AssessInfoDto assessInfoDto) {
        log.info("[selectList]assessInfoDto={}", JSONUtil.toJsonStr(assessInfoDto));
        LambdaQueryWrapper<AssessInfo> queryWrapper = this.getAssessInfoLambdaQueryWrapper(assessInfoDto);
        IPage<AssessInfoVo> assessInfoVoIPage = baseMapper.selectVoPage(iPage, queryWrapper);
        log.info("[selectList]-assessInfoVoIPage={}", JSONUtil.toJsonStr(assessInfoVoIPage));
        return assessInfoVoIPage;
    }

    @NotNull
    private LambdaQueryWrapper<AssessInfo> getAssessInfoLambdaQueryWrapper(AssessInfoDto assessInfoDto) {
        LambdaQueryWrapper<AssessInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(assessInfoDto.getTenantId()), AssessInfo::getTenantId, assessInfoDto.getTenantId());
        queryWrapper.like(StrUtil.isNotBlank(assessInfoDto.getEldName()), AssessInfo::getEldName, assessInfoDto.getEldName());
        queryWrapper.eq(StrUtil.isNotBlank(assessInfoDto.getEldIdType()), AssessInfo::getEldIdType, assessInfoDto.getEldIdType());
        queryWrapper.like(StrUtil.isNotBlank(assessInfoDto.getEldIdNumber()), AssessInfo::getEldIdNumber, assessInfoDto.getEldIdNumber());
        queryWrapper.eq(StrUtil.isNotBlank(assessInfoDto.getEldId()), AssessInfo::getEldId, assessInfoDto.getEldId());
        queryWrapper.eq(StrUtil.isNotBlank(assessInfoDto.getTemplateCategoryId()), AssessInfo::getTemplateCategoryId, assessInfoDto.getTemplateCategoryId());
        queryWrapper.eq(ObjUtil.isNotNull(assessInfoDto.getAssessType()), AssessInfo::getAssessType, assessInfoDto.getAssessType());
        queryWrapper.eq(ObjUtil.isNotNull(assessInfoDto.getAssessStatus()), AssessInfo::getAssessStatus, assessInfoDto.getAssessStatus());
        queryWrapper.ge(ObjUtil.isNotNull(assessInfoDto.getStartDate()), AssessInfo::getAssessDate, assessInfoDto.getStartDate());
        queryWrapper.le(ObjUtil.isNotNull(assessInfoDto.getEndDate()), AssessInfo::getAssessDate, assessInfoDto.getEndDate());
        queryWrapper.eq(AssessInfo::getDeleted, UN_DELETED);
        if (ObjUtil.equal(assessInfoDto.getAssessCycle(), 0)){
            DateTime compareDate = DateUtil.offsetMonth(new Date(), 12);
            queryWrapper.le(AssessInfo::getAssessDate, compareDate);
        }
        if (ObjUtil.equal(assessInfoDto.getAssessCycle(), 1)){
            DateTime compareDate = DateUtil.offsetMonth(new Date(), 12);
            queryWrapper.ge(AssessInfo::getAssessDate, compareDate);
        }
        queryWrapper.orderByAsc(AssessInfo::getAssessStatus);
        queryWrapper.orderByDesc(AssessInfo::getAssessDate);
        return queryWrapper;
    }

    public AssessInfoVo selectAssessInfoVoWithParams(AssessInfoDto assessInfoDto) {
        AssessInfoVo assessInfoVo = new AssessInfoVo();
        AssessInfo assessInfo = this.selectAssessInfoWithParams(assessInfoDto);
        BeanUtil.copyProperties(assessInfo, assessInfoVo);
        return assessInfoVo;
    }

    /**
     * 根据条件查询评估列表
     */
    public AssessInfo selectAssessInfoWithParams(AssessInfoDto assessInfoDto) {
        // 查询长者未完成的评估信息
        LambdaQueryWrapper<AssessInfo> query = Wrappers.lambdaQuery();
        query.eq(StrUtil.isNotBlank(assessInfoDto.getAssessNo()), AssessInfo::getAssessNo, assessInfoDto.getAssessNo());
        query.eq(ObjUtil.isNotEmpty(assessInfoDto.getAssessStatus()), AssessInfo::getAssessStatus, assessInfoDto.getAssessStatus());
        query.eq(StrUtil.isNotBlank(assessInfoDto.getEldName()), AssessInfo::getEldName, assessInfoDto.getEldName());
        query.eq(ObjUtil.isNotEmpty(assessInfoDto.getEldSex()), AssessInfo::getEldSex, assessInfoDto.getEldSex());
        query.eq(StrUtil.isNotBlank(assessInfoDto.getEldIdType()), AssessInfo::getEldIdType, assessInfoDto.getEldIdType());
        query.eq(StrUtil.isNotBlank(assessInfoDto.getEldIdNumber()), AssessInfo::getEldIdNumber, assessInfoDto.getEldIdNumber());
        query.eq(StrUtil.isNotBlank(assessInfoDto.getTemplateId()), AssessInfo::getTemplateId, assessInfoDto.getTemplateId());
        query.eq(StrUtil.isNotBlank(assessInfoDto.getTenantId()), AssessInfo::getTenantId, assessInfoDto.getTenantId());
        query.orderByDesc(AssessInfo::getAssessDate);
        query.orderByDesc(AssessInfo::getAddTime);
        query.orderByDesc(AssessInfo::getId);
        query.eq(AssessInfo::getDeleted, UN_DELETED);
        query.last("limit 1");

        String eldId = StringUtil.isNotEmpty(assessInfoDto.getElderId()) ? assessInfoDto.getElderId() : assessInfoDto.getEldId();
        query.eq(StrUtil.isNotBlank(eldId), AssessInfo::getEldId, eldId);

        return this.getOne(query);
    }

    @Override
    public AssessInfoVo queryByAssessNo(AssessInfoDto assessInfoDto) {
        AssessInfoVo assessInfo = this.getAssessInfo(new GetAssessInfoReqDto(assessInfoDto.getAssessNo()));
        if (assessInfo == null) {
            throw new EchaseException("没有查询到该评估数据");
        }

        AssessInfoVo assessInfoVo = new AssessInfoVo();
        BeanUtils.copyProperties(assessInfo, assessInfoVo);

        this.fillAssessResultJson(assessInfoDto.getAssessNo(), assessInfoVo);
        this.fillAssessReasonData(assessInfoVo);

        return assessInfoVo;
    }

    @Override
    public AssessInfoVo getAssessInfo(GetAssessInfoReqDto getAssessInfoReqDto) {
        AssessInfoDto assessInfoDto = new AssessInfoDto();
        BeanUtil.copyProperties(getAssessInfoReqDto, assessInfoDto);
        AssessInfo assessInfo = this.selectAssessInfoWithParams(assessInfoDto);
        AssessInfoVo assessInfoVo = new AssessInfoVo();
        BeanUtil.copyProperties(assessInfo, assessInfoVo);
        return assessInfoVo;
    }

    /**
     * 填充评估结果
     */
    private void fillAssessResultJson(String assessNo, AssessInfoVo assessInfoVo) {
        log.info("[fillAssessResultJson]-assessNo={},assessInfoVo={}", assessNo, JSONUtil.toJsonStr(assessInfoVo));
        LambdaQueryWrapper<AssessInfoResult> resultLambdaQueryWrapper = Wrappers.lambdaQuery();
        resultLambdaQueryWrapper.eq(AssessInfoResult::getAssessNo, assessNo);
        resultLambdaQueryWrapper.eq(AssessInfoResult::getDeleted, UN_DELETED);
        AssessInfoResult assessInfoResult = assessInfoResultService.getOne(resultLambdaQueryWrapper);
        log.info("[AssessInfoResult-getOne]-assessInfoResult={}", JSONUtil.toJsonStr(assessInfoResult));
        if (assessInfoResult != null) {
            assessInfoVo.setResultJson(assessInfoResult.getResultJson());
        }
    }

    /**
     * 构建评估原因表单
     */
    public void fillAssessReasonData(AssessInfoVo assessInfoVo) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("☐");

        StringBuilder stringBuilder1 = new StringBuilder();
        stringBuilder1.append("☑");

        Integer assessType = assessInfoVo.getAssessType();
        if (IntegerUtil.equalsAny(assessType, AssessConstant.AssessType.TYPE_1)) {
            assessInfoVo.setAssessType1(stringBuilder1.toString());
            assessInfoVo.setAssessType2(stringBuilder.toString());
            assessInfoVo.setAssessType3(stringBuilder.toString());
            assessInfoVo.setAssessType4(stringBuilder.toString());
            assessInfoVo.setAssessType5(stringBuilder.toString());
        }
        if (IntegerUtil.equalsAny(assessType, AssessConstant.AssessType.TYPE_2)) {
            assessInfoVo.setAssessType1(stringBuilder.toString());
            assessInfoVo.setAssessType2(stringBuilder1.toString());
            assessInfoVo.setAssessType3(stringBuilder.toString());
            assessInfoVo.setAssessType4(stringBuilder.toString());
            assessInfoVo.setAssessType5(stringBuilder.toString());
        }
        if (IntegerUtil.equalsAny(assessType, AssessConstant.AssessType.TYPE_3)) {
            assessInfoVo.setAssessType1(stringBuilder.toString());
            assessInfoVo.setAssessType2(stringBuilder.toString());
            assessInfoVo.setAssessType3(stringBuilder1.toString());
            assessInfoVo.setAssessType4(stringBuilder.toString());
            assessInfoVo.setAssessType5(stringBuilder.toString());
        }
        if (IntegerUtil.equalsAny(assessType, AssessConstant.AssessType.TYPE_4)) {
            assessInfoVo.setAssessType1(stringBuilder.toString());
            assessInfoVo.setAssessType2(stringBuilder.toString());
            assessInfoVo.setAssessType3(stringBuilder.toString());
            assessInfoVo.setAssessType4(stringBuilder1.toString());
            assessInfoVo.setAssessType5(stringBuilder.toString());
        }
        if (IntegerUtil.equalsAny(assessType, AssessConstant.AssessType.TYPE_5)) {
            assessInfoVo.setAssessType1(stringBuilder.toString());
            assessInfoVo.setAssessType2(stringBuilder.toString());
            assessInfoVo.setAssessType3(stringBuilder.toString());
            assessInfoVo.setAssessType4(stringBuilder.toString());
            assessInfoVo.setAssessType5(stringBuilder1.toString());
        }
    }

    @Override
    public List<String> getHistoryAssessAddressList(String orgId) {
        LambdaQueryWrapper<AssessInfo> query = Wrappers.lambdaQuery();
        query.select(AssessInfo::getAssessAddress);
        query.eq(AssessInfo::getDeleted, UN_DELETED);
        query.eq(AssessInfo::getTenantId, orgId);
        query.apply("TRIM(assess_address) != ''");
        query.orderByDesc(AssessInfo::getAddTime);
        List<String> assessAddressList = this.baseMapper.selectObjs(query);
        List<String> returnList = new ArrayList<>();
        for (String assessAddress : assessAddressList) {
            if (returnList.size() == 5) {
                break;
            }
            if (!returnList.contains(assessAddress)) {
                returnList.add(assessAddress);
            }
        }
        return returnList;
    }

    /**
     * 确认评估 更新评估结果 (assessStatus 1 暂存 2 完成)
     *
     * @param assessInfoDto 评估信息
     * @return @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AssessBaseResDto updateResult(AssessInfoDto assessInfoDto) {
        Assert.notBlank(assessInfoDto.getAssessNo(), "评估编号不能为空！");
        Assert.notBlank(assessInfoDto.getTemplateId(), "评估模板id不能为空！");

        assessInfoDto.initProperties();
        assessInfoDto.initPropertiesFromResultJson();

        AssessInfoVo assessInfoExist = this.getAssessInfo(new GetAssessInfoReqDto(assessInfoDto.getAssessNo()));
        if (ObjUtil.isEmpty(assessInfoExist)) {
            throw new EchaseException("评估信息不存在！");
        }

        AssessInfoResult assessInfoResult = assessInfoResultService.getAssessInfoResult(new GetAssessInfoReqDto(assessInfoDto.getAssessNo()));
        if (assessInfoResult != null && StringUtil.isNotEmpty(assessInfoResult.getAssessNo())) {
            this.updateAssessInfoResult(assessInfoDto, assessInfoResult);
        }else {
            this.saveAssessInfoResult(assessInfoDto);
        }

        this.updateAssessInfo(assessInfoDto);
        return new AssessBaseResDto(assessInfoDto.getTenantId(), assessInfoDto.getTenantId(), assessInfoDto.getEldId(), assessInfoDto.getAssessNo(), assessInfoDto.getAssessStatus());
    }

    private void saveAssessInfoResult(AssessInfoDto assessInfoDto) {
        AssessInfoResult assessInfoResult;
        assessInfoResult = new AssessInfoResult();
        assessInfoResult.setUcId(UcCommonUtils.generateUcId());
        assessInfoResult.setAssessNo(assessInfoDto.getAssessNo());
        assessInfoResult.setResultJson(JSON.toJSONString(assessInfoDto.getResultJson()));
        assessInfoResult.setTemplateId(assessInfoDto.getTemplateId());
        assessInfoResult.setTenantId(assessInfoDto.getTenantId());
        assessInfoResult.setDeleted(UN_DELETED);
        assessInfoResult.setAddTime(new Date());
        assessInfoResult.setStatus(assessInfoDto.getAssessStatus());
        assessInfoResultService.save(assessInfoResult);
    }

    private void updateAssessInfoResult(AssessInfoDto assessInfoDto, AssessInfoResult assessInfoResult) {
        LambdaUpdateWrapper<AssessInfoResult> updateResult = Wrappers.lambdaUpdate();
        updateResult.eq(AssessInfoResult::getTenantId, assessInfoDto.getTenantId());
        updateResult.eq(AssessInfoResult::getAssessNo, assessInfoDto.getAssessNo());
        assessInfoResult.setResultJson(JSON.toJSONString(assessInfoDto.getResultJson()));
        assessInfoResult.setUpdateTime(new Date());
        if (IntegerUtil.equalsAny(assessInfoDto.getAssessStatus(), COMPLETE)) {
            assessInfoResult.setStatus(COMPLETE);
        }
        assessInfoResultService.update(assessInfoResult, updateResult);
    }

    /**
     * 评估完成的处理逻辑
     */
    public void updateAssessInfo(AssessInfoDto assessInfoDto) {
        String userId = String.valueOf(LoginHelper.getUserId());
        String tenantId = LoginHelper.getOrgId();

        //更新评估状态
        AssessInfo assessInfo = new AssessInfo();
        assessInfo.setUpdateBy(userId);
        assessInfo.setUpdateTime(new Date());
        assessInfo.setAssessStatus(assessInfoDto.getAssessStatus());
        assessInfo.setAssessResult(assessInfoDto.getAssessResult());
        assessInfo.setUltimateAbilityLevel(assessInfoDto.getAssessResult());
        assessInfo.setEldName(assessInfoDto.getEldName());

        LambdaUpdateWrapper<AssessInfo> update = Wrappers.lambdaUpdate();
        update.eq(AssessInfo::getTenantId, tenantId);
        update.eq(AssessInfo::getAssessNo, assessInfoDto.getAssessNo());
        this.update(assessInfo, update);
    }

    /**
     * 根据评估编号查询评估打印信息（新）
     *
     * @param assessNo 评估编号
     * @return @return {@link List }<{@link AssessInfoVo }>
     */
    @Override
    public JSONObject queryAssessPrintData(String assessNo, String key) throws Exception {
        LambdaQueryWrapper<AssessInfoResult> resultLambdaQueryWrapper = Wrappers.lambdaQuery();
        resultLambdaQueryWrapper.eq(AssessInfoResult::getAssessNo, assessNo);
        resultLambdaQueryWrapper.eq(AssessInfoResult::getDeleted, UN_DELETED);
        AssessInfoResult assessInfoResult = assessInfoResultService.getOne(resultLambdaQueryWrapper);
        log.info("[queryAssessPrintData]-[getOne],assessInfoResult={}", JSONUtil.toJsonStr(assessInfoResult));
        if (ObjUtil.isNull(assessInfoResult)) {
            throw new EchaseException("没有查询到该评估数据");
        }

        JSONObject assessDate = JSON.parseObject(assessInfoResult.getResultJson());
        AssessTemplateDto assessTemplateDto = new AssessTemplateDto();
        assessTemplateDto.setUcId(assessInfoResult.getTemplateId());
        assessTemplateDto.setOrgId(assessInfoResult.getTenantId());
        log.info("[queryAssessPrintData]-[getAssessTemplateInfo],assessTemplateDto={}", JSONUtil.toJsonStr(assessTemplateDto));
        AssessTemplateDto assessTemplate = this.assessTemplateService.getAssessTemplateInfo(assessTemplateDto);
        if (ObjUtil.isNull(assessTemplate)) {
            throw new EchaseException("评估模版不存在");
        }

        JSONObject pageContent = JSON.parseObject(assessTemplate.getFormContent());
        return JSONNodeUtil.dataConvert(pageContent, assessDate, key);
    }

    /**
     * 人员评估情况中的服药情况（新）
     * */
    @Override
    public AssesElderMedicineVo initAssesElderMedicineVo(JSONArray dataArray) {
        AssesElderMedicineVo medicineVo = new AssesElderMedicineVo();
        if (ObjUtil.isEmpty(dataArray)) {
            return medicineVo;
        }

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject dataObj = dataArray.getJSONObject(i);

            if (i == 0) {
                medicineVo.setMedicineName(dataObj.getString(KEY_input63872));
                medicineVo.setMedicineUse(dataObj.getString(KEY_input99538));
                medicineVo.setMedicineDose(dataObj.getString(KEY_input54312));
                medicineVo.setMedicineFreq(dataObj.getString(KEY_input19197));
            }
            if (i == 1) {
                medicineVo.setMedicineName1(dataObj.getString(KEY_input63872));
                medicineVo.setMedicineUse1(dataObj.getString(KEY_input99538));
                medicineVo.setMedicineDose1(dataObj.getString(KEY_input54312));
                medicineVo.setMedicineFreq1(dataObj.getString(KEY_input19197));
            }
            if (i == 2) {
                medicineVo.setMedicineName2(dataObj.getString(KEY_input63872));
                medicineVo.setMedicineUse2(dataObj.getString(KEY_input99538));
                medicineVo.setMedicineDose2(dataObj.getString(KEY_input54312));
                medicineVo.setMedicineFreq2(dataObj.getString(KEY_input19197));
            }
            if (i == 3) {
                medicineVo.setMedicineName3(dataObj.getString(KEY_input63872));
                medicineVo.setMedicineUse3(dataObj.getString(KEY_input99538));
                medicineVo.setMedicineDose3(dataObj.getString(KEY_input54312));
                medicineVo.setMedicineFreq3(dataObj.getString(KEY_input19197));
            }
            if (i == 4) {
                medicineVo.setMedicineName4(dataObj.getString(KEY_input63872));
                medicineVo.setMedicineUse4(dataObj.getString(KEY_input99538));
                medicineVo.setMedicineDose4(dataObj.getString(KEY_input54312));
                medicineVo.setMedicineFreq4(dataObj.getString(KEY_input19197));
            }
        }
        return null;
    }

    /**
     * 删除评估信息
     *
     * @param assessNo 评估编号
     * @return @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String assessNo) {
        String userId = String.valueOf(LoginHelper.getUserId());
        String tenantId = LoginHelper.getOrgId();

        //更新评估主表
        LambdaUpdateWrapper<AssessInfo> update = Wrappers.lambdaUpdate();
        update.eq(AssessInfo::getTenantId, tenantId);
        update.eq(AssessInfo::getAssessNo, assessNo);
        AssessInfo assessInfo = new AssessInfo();
        assessInfo.setUpdateBy(userId);
        assessInfo.setUpdateTime(new Date());
        assessInfo.setDeleted(DELETED);
        boolean update1 = this.update(assessInfo, update);

        //更新评估结果表
        LambdaUpdateWrapper<AssessInfoResult> updateResult = Wrappers.lambdaUpdate();
        updateResult.eq(AssessInfoResult::getTenantId, tenantId);
        updateResult.eq(AssessInfoResult::getAssessNo, assessNo);
        AssessInfoResult assessInfoResult = new AssessInfoResult();
        assessInfoResult.setDeleted(DELETED);
        assessInfoResult.setUpdateTime(new Date());
        assessInfoResult.setUpdateBy(userId);
        boolean update2 = assessInfoResultService.update(assessInfoResult, updateResult);

        return update1 && update2;
    }

    /**
     * 开始评估插入基本信息(因为有可能在不预约的情况下直接评估，所以不能校验用户信息)
     *
     * @param assessInfoDto 评估信息
     * @return @return boolean
     */
    @Override
    public AssessBaseResDto add(AssessInfoDto assessInfoDto) {
        if (StringUtil.isBlank(assessInfoDto.getTemplateId())) {
            throw new EchaseException(400, "评估模板ID不能为空！");
        }

        assessInfoDto.initProperties();

        AssessInfo assessInfo = new AssessInfo();
        BeanUtils.copyProperties(assessInfoDto, assessInfo);

        // 校验该机构下，该用户是否存在未完成评估
        this.checkExistAssess(assessInfoDto);

        if (StrUtil.isNotBlank(assessInfoDto.getAssessNo())) {
            AssessInfoDto assessInfoDto_2 = new AssessInfoDto();
            assessInfoDto_2.setTenantId(assessInfoDto.getTenantId());
            assessInfoDto_2.setAssessNo(assessInfoDto.getAssessNo());
            AssessInfo assessInfo_exist2 = this.selectAssessInfoWithParams(assessInfoDto_2);
            if (ObjUtil.isNotEmpty(assessInfo_exist2)) {
                if (ObjUtil.equal(assessInfo_exist2.getAssessStatus(), COMPLETE)) {
                    throw new EchaseException(400, "评估已完成不能修改！");
                }
                if (ObjUtil.equal(assessInfo_exist2.getAssessStatus(), UN_COMPLETE)) {
                    this.updateAssessInfoByNo(assessInfo);
                    return new AssessBaseResDto(assessInfoDto.getTenantId(), assessInfoDto.getTenantId(), assessInfoDto.getEldId(), assessInfoDto.getAssessNo(), assessInfo_exist2.getAssessStatus());
                }
            }
        } else {
            String assessNo = this.generatorAssessNo();
            assessInfo.setAssessNo(assessNo);
        }
        if (ObjUtil.isEmpty(assessInfoDto.getAssessDate())) {
            assessInfo.setAssessDate(LocalDate.now());
        }
        // 是否校验长者信息和根据长者信息查询评估信息
        assessInfo.setUcId(UcCommonUtils.generateUcId());
        assessInfo.setAddTime(new Date());
        assessInfo.setDeleted(UN_DELETED);
        assessInfo.setAssessStatus(UN_COMPLETE);
        assessInfo.setEldType(assessInfoDto.getType());

        this.save(assessInfo);
        return new AssessBaseResDto(assessInfoDto.getTenantId(), assessInfoDto.getTenantId(), assessInfoDto.getEldId(), assessInfoDto.getAssessNo(), UN_COMPLETE);
    }

    /**
     * 根据【tenantId】【assessNo】修改评估信息
     */
    private void updateAssessInfoByNo(AssessInfo assessInfo) {
        Assert.notBlank(assessInfo.getTenantId(), "机构ID不能为空！");
        Assert.notBlank(assessInfo.getAssessNo(), "评估编号为空不能修改评估！");
        LambdaUpdateWrapper<AssessInfo> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(AssessInfo::getTenantId, assessInfo.getTenantId());
        updateWrapper.eq(AssessInfo::getAssessNo, assessInfo.getAssessNo());
        assessInfo.setUpdateTime(new Date());
        assessInfo.setUpdateBy(String.valueOf(LoginHelper.getUserId()));
        this.update(assessInfo, updateWrapper);
    }

    /**
     * 根据长者id查询未完成评估信息（新）
     */
    @Override
    public AssessInfoVo unCompleteAssess(AssessInfoDto assessInfoDto) {
        // 查询长者未完成的评估信息
        assessInfoDto.setTenantId(LoginHelper.getOrgId());
        assessInfoDto.setAssessStatus(UN_COMPLETE);
        AssessInfoVo assessInfoVo = this.selectAssessInfoVoWithParams(assessInfoDto);

        // 不存在评估信息时返回生成的评估编号
        if (assessInfoVo == null || StringUtil.isEmpty(assessInfoVo.getAssessNo())) {
            assessInfoVo = new AssessInfoVo();
            assessInfoVo.setAssessNo(generatorAssessNo());
        }
        return assessInfoVo;
    }

    private String generatorAssessNo() {
        String assessNo = "Y" + (int) ((Math.random() * 9 + 1) * 100000) + (int) ((Math.random() * 9 + 1) * 100000);
        //机构内 判断评估编号是否重复。重复则重新生成
        LambdaQueryWrapper<AssessInfo> query = Wrappers.lambdaQuery();
        query.eq(AssessInfo::getTenantId, LoginHelper.getOrgId());
        query.eq(AssessInfo::getAssessNo, assessNo);
        AssessInfo assessEldResult = this.getOne(query);
        if (assessEldResult != null && !StringUtil.isEmpty(assessEldResult.getAssessNo())) {
            return generatorAssessNo();
        }
        return assessNo;
    }

    /**
     * 校验该机构下，该用户是否存在未完成评估
     */
    private void checkExistAssess(AssessInfoDto assessInfoDto) {
        AssessInfoDto assessInfoDto_1 = new AssessInfoDto();
        BeanUtils.copyProperties(assessInfoDto, assessInfoDto_1);
        assessInfoDto_1.setTenantId(assessInfoDto.getOrgId());
        assessInfoDto_1.setAssessStatus(UN_COMPLETE);
        AssessInfo assessInfo_exist1 = this.selectAssessInfoWithParams(assessInfoDto_1);
        if (ObjUtil.isNotEmpty(assessInfo_exist1) && StrUtil.isNotBlank(assessInfo_exist1.getTemplateId())) {
            throw new EchaseException("该长者存在未完成的" + assessInfo_exist1.getTemplateName() + "，请完成后再进行新的评估");
        }
    }

}
